1
2
3 package samples;
4
5 import java.beans.*;
6 import java.lang.reflect.*;
7 import net.sf.cglib.proxy.*;
8
9 /***
10 *
11 * @author baliuka
12 */
13 public class Beans implements MethodInterceptor {
14
15 private PropertyChangeSupport propertySupport;
16
17 public void addPropertyChangeListener(PropertyChangeListener listener) {
18
19 propertySupport.addPropertyChangeListener(listener);
20
21 }
22
23 public void removePropertyChangeListener(PropertyChangeListener listener) {
24 propertySupport.removePropertyChangeListener(listener);
25 }
26
27 public static Object newInstance( Class clazz ){
28 try{
29 Beans interceptor = new Beans();
30 Enhancer e = new Enhancer();
31 e.setSuperclass(clazz);
32 e.setCallback(interceptor);
33 Object bean = e.create();
34 interceptor.propertySupport = new PropertyChangeSupport( bean );
35 return bean;
36 }catch( Throwable e ){
37 e.printStackTrace();
38 throw new Error(e.getMessage());
39 }
40
41 }
42
43 static final Class C[] = new Class[0];
44 static final Object emptyArgs [] = new Object[0];
45
46
47 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
48 Object retValFromSuper = null;
49 try {
50 if (!Modifier.isAbstract(method.getModifiers())) {
51 retValFromSuper = proxy.invokeSuper(obj, args);
52 }
53 } finally {
54 String name = method.getName();
55 if( name.equals("addPropertyChangeListener")) {
56 addPropertyChangeListener((PropertyChangeListener)args[0]);
57 }else if ( name.equals( "removePropertyChangeListener" ) ){
58 removePropertyChangeListener((PropertyChangeListener)args[0]);
59 }
60 if( name.startsWith("set") &&
61 args.length == 1 &&
62 method.getReturnType() == Void.TYPE ){
63
64 char propName[] = name.substring("set".length()).toCharArray();
65
66 propName[0] = Character.toLowerCase( propName[0] );
67 propertySupport.firePropertyChange( new String( propName ) , null , args[0]);
68
69 }
70 }
71 return retValFromSuper;
72 }
73
74 public static void main( String args[] ){
75
76 Bean bean = (Bean)newInstance( Bean.class );
77
78 bean.addPropertyChangeListener(
79 new PropertyChangeListener(){
80 public void propertyChange(PropertyChangeEvent evt){
81 System.out.println(evt);
82 }
83 }
84 );
85
86 bean.setSampleProperty("TEST");
87
88
89 }
90
91
92 }
This page was automatically generated by Maven